package com.soft.collateral.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.soft.collateral.constant.MessageConstant;
import com.soft.collateral.entity.User;
import com.soft.collateral.result.Result;
import com.soft.collateral.service.UserService;
import com.soft.collateral.utils.JwtHelper;
import com.soft.collateral.vo.PageQueryVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @desc TODO
 * @date 2025/7/24
 */
@RestController
@RequestMapping("/admin/user")
@Slf4j
@Api(tags = "后台系统-用户管理接口")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final FileController fileController;

    @ApiOperation("获取用户信息")
    @GetMapping("info")
    public Result getUserInfo(@RequestHeader("Authorization") String authorization) {
        //请求头  以Authorization作为键，以Bearer accessToken作为值
        if(StringUtils.hasLength(authorization)){
            String accessToken = authorization.substring(7);
            //获取用户ID
            Long userId = JwtHelper.getUserId(accessToken);
            //查询用户信息
            User user = userService.getById(userId.intValue());
            if(!ObjectUtils.isEmpty(user)){
                return new Result(true , MessageConstant.GET_USER_SUCCESS , user);
            }
        }
        return new Result(false , MessageConstant.GET_USER_FAIL);
    }

    @ApiOperation("分页条件查询用户列表")
    @PostMapping("page")
    public Result page(@RequestBody PageQueryVO vo){
        Page<User> userPage = userService.page(vo);
        if(userPage!=null && userPage.getTotal()>0){
            return new Result(true , MessageConstant.GET_USER_SUCCESS , userPage);
        }
        return new Result(false , MessageConstant.GET_USER_FAIL);
    }

    @ApiOperation("新增用户")
    @PostMapping("create")
    public Result create(@RequestParam("roleIds") Integer[] roleIds,
                         @RequestParam(value = "avatarFile", required = false) MultipartFile avatarFile,
                         @RequestBody User user) {

        // 处理头像上传
        if (avatarFile != null && !avatarFile.isEmpty()) {
            Result uploadResult = fileController.upload(avatarFile);
            if (uploadResult.isSuccess()) {
                user.setAvatar(uploadResult.getData().toString());
            }
        }

        boolean flag = userService.save(roleIds, user);
        if(flag){
            return new Result(true ,MessageConstant.SAVE_USER_SUCCESS);
        }
        return new Result(false ,MessageConstant.SAVE_USER_FAIL);
    }

    @ApiOperation("根据id查询用户")
    @GetMapping("{id}")
    public Result getById(@PathVariable Integer id) {
        User user = userService.getById(id);
        if(user!=null){
            return new Result(true ,MessageConstant.GET_USER_SUCCESS , user);
        }
        return new Result(false ,MessageConstant.GET_USER_FAIL);
    }

    @ApiOperation("根据用户id查询关联的角色信息")
    @GetMapping("findRoles/{id}")
    public Result findRolesById(@PathVariable Integer id) {

        List<Integer> rolesId = userService.findRolesById(id);
        if(!CollectionUtils.isEmpty(rolesId)){
            return new Result(true ,MessageConstant.GET_ROLE_SUCCESS , rolesId);
        }
        return new Result(false ,MessageConstant.GET_ROLE_FAIL);
    }

    @ApiOperation("更新用户信息")
    @PutMapping("update")
    public Result update(@RequestParam("roleIds") Integer[] roleIds,
                         @RequestParam(value = "avatarFile", required = false) MultipartFile avatarFile,
                         @RequestBody User user) {

        // 处理头像更新
        if (avatarFile != null && !avatarFile.isEmpty()) {
            Result uploadResult = fileController.upload(avatarFile);
            if (uploadResult.isSuccess()) {
                // 删除旧头像
                if (StringUtils.hasText(user.getAvatar())) {
                    fileController.delete(user.getAvatar());
                }
                user.setAvatar(uploadResult.getData().toString());
            }
        }

        boolean flag = userService.update(roleIds, user);
        if(flag){
            return new Result(true ,MessageConstant.UPDATE_USER_SUCCESS);
        }
        return new Result(false ,MessageConstant.UPDATE_USER_FAIL);
    }

    @ApiOperation("根据id删除用户")
    @DeleteMapping("{id}")
    public Result deleteById(@PathVariable Integer id) {
        boolean flag = userService.removeById(id);
        if(flag){
            return new Result(true ,MessageConstant.DELETE_USER_SUCCESS);
        }
        return new Result(false ,MessageConstant.DELETE_USER_FAIL);
    }
}
